from requests.exceptions import HTTPError, ConnectionError, Timeout, RequestException
import json
import requests
from requests.adapters import HTTPAdapter
import datetime
import traceback

import logging
logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)  # 设置日志级别为 DEBUG，包括 bug 级别


class Client(object):
    def __init__(self):

        self.session = requests.Session()
        self.session.mount(
            'https://', HTTPAdapter(pool_connections=50, pool_maxsize=100))
        if not self.session:
            raise

    def make_request(self, url, method="GET", data=None, headers=None, timeout=5, verify=True):
        """
        Sends a http request and handle exceptions.
        Parameters:
            url (str): The URL to send the request to.
            method (str): The HTTP method to use. Default is "GET".
            data (dict): The JSON data to send. Default is None.
            headers (dict): The HTTP headers to send. Default is None.
            timeout (int): The timeout for the request. Default is 5 seconds.
        Returns:
            response (Response): The Response object.
        """
        try:
            if method.upper() == "GET":
                response = self.session.get(url, params=data, headers=headers,
                                            timeout=timeout, verify=verify)
            elif method.upper() == "POST":
                response = self.session.post(
                    url, data=data, headers=headers, timeout=timeout, verify=verify)
            # Add other HTTP methods (PUT, DELETE, etc.) here if needed

            # If the response was successful, no Exception will be raised
            response.raise_for_status()
        except HTTPError as http_err:
            error_info = traceback.format_exc()
            logger.error(
                f'HTTP error occurred: {http_err} error_info:  {error_info}')
        except ConnectionError as conn_err:
            error_info = traceback.format_exc()
            logger.error(
                f'Connection error occurred: {conn_err} error_info:  {error_info}')
        except Timeout as timeout_err:
            error_info = traceback.format_exc()
            logger.error(
                f'Timeout error occurred: {timeout_err} error_info:  {error_info}')
        except RequestException as req_err:
            error_info = traceback.format_exc()
            logger.error(
                f'Request error occurred: {req_err} error_info:  {error_info}')
        except Exception as err:
            error_info = traceback.format_exc()
            logger.error(
                f'Other error occurred: {err} error_info:  {error_info}')
        else:
            logger.error('Success!')
            return response
        return None


def timeshow(text='当前时间'):

    # 获取当前时间
    now = datetime.datetime.now()

    # 获取当前时间的毫秒级时间戳
    timestamp = round(now.timestamp(), 3)
    # 获取当前时间字符串格式
    timeformat = now.strftime('%Y-%m-%d %H:%M:%S')
    microseconds = now.microsecond
    milliseconds = round(microseconds / 1000)
    timeformat = f'{timeformat}.{milliseconds:03d}'

    # 输出当前时间
    # logger.error(f'{text}:{timeformat}')
    return now, timestamp, timeformat


client = Client()

if __name__ == "__main__":
    # Use the function:
    # url = 'https://example.com1'
    # method = "GET"
    # headers = {'Content-Type': 'application/json'}
    # now1 = timeshow(f'start:    {url}')
    # r = make_request(url, method=method, headers=headers, timeout=1)
    # now2 = timeshow(f'end:  {url}')
    # if r:
    #     logger.error(
    #         f'[---start\nget_time:   {now1}\n耗时:   {now2-now1}\nurl:    {url}\n结果:   {r.text}\n---end]')
    # else:
    #     logger.error(
    #         f'[---start\nget_time:   {now1}\n耗时:   {now2-now1}\nurl:    {url}\n结果:   失败(具体原因见前面的错误警告)\n---end]')

    # method = "GET"
    # headers = {
    #     "Content-Type": "application/json",
    #     "Accept": "application/json",
    #     "Authorization": "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJjIjoiNWZlMWE0MWQxZmU5OGUwNjE5NTc2ODk5IiwidSI6ImZmcWhkdnBkMTAyYzZkMGEiLCJyIjoiR0xCNWU2NTRiYUczIiwidCI6ImEiLCJpYXQiOjE3MDE5MzQ3MTksImV4cCI6MTcwMjUzOTUxOX0.0pTkSLjoR8Zjz678Kgt2v5il--YJJQXMUhpZQ6K7FfYKpLfhvn2GuUuLC3r_QYNpgj5wKdjoSqxT7yLgVACNqnrwqmJV57k9PweskgbaKUbKEkGCXLzPKK7hzYnPPOPpu0P0InWMD6G2FKDczQ59_JsmKnGSXCVYsHoO6QDi3G0",
    #     "appid": "Nlp",
    #     "Host": "api-app.dc-cn.cn.ecouser.net"
    # }
    # msgdata = {
    #     "userid": "ffqhdvpd102c6d0a"
    # }
    # url = f'https://120.26.214.215/api/appsvr/GetGlobalDeviceList'
    # now1 = timeshow(f'start:    {url}')
    # r = make_request(url, method=method, data=msgdata, headers=headers,
    #                  timeout=1, verify=False)
    # now2 = timeshow(f'end:  {url}')
    # if r:
    #     logger.error(
    #         f'[---start\nget_time:   {now1}\n耗时:   {now2-now1}\nurl:    {url}\n结果:   {r.text}\n---end]')
    # else:
    #     logger.error(
    #         f'[---start\nget_time:   {now1}\n耗时:   {now2-now1}\nurl:    {url}\n结果:   失败(具体原因见前面的错误警告)\n---end]')

    method = "GET"
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJjIjoiNWZlMWE0MWQxZmU5OGUwNjE5NTc2ODk5IiwidSI6ImZmcWhkdnBkMTAyYzZkMGEiLCJyIjoiR0xCNWU2NTRiYUczIiwidCI6ImEiLCJpYXQiOjE3MDE5MzQ3MTksImV4cCI6MTcwMjUzOTUxOX0.0pTkSLjoR8Zjz678Kgt2v5il--YJJQXMUhpZQ6K7FfYKpLfhvn2GuUuLC3r_QYNpgj5wKdjoSqxT7yLgVACNqnrwqmJV57k9PweskgbaKUbKEkGCXLzPKK7hzYnPPOPpu0P0InWMD6G2FKDczQ59_JsmKnGSXCVYsHoO6QDi3G0",
        "appid": "Nlp",
    }
    msgdata = {
        "userid": "ffqhdvpd102c6d0a"
    }
    url = f'https://api-app.dc-cn.cn.ecouser.net/api/appsvr/GetGlobalDeviceList'
    now1 = timeshow(f'start:    {url}')
    r = client.make_request(url, method=method, data=msgdata, headers=headers,
                            timeout=1.5, verify=True)
    now2 = timeshow(f'end:  {url}')
    if r:
        logger.error(
            f'[---start\nget_time:   {now2[1]}\n耗时:   {now2[1]-now1[1]}\nurl:    {url}\n结果:   {r.text}\n---end]')
        try:
            result = json.loads(r.text)
            logger.error(result)
        except json.JSONDecodeError:
            logger.error("Decoding JSON has failed")
    else:
        logger.error(
            f'[---start\nget_time:   {now1[2]}\n耗时:   {now2[1]-now1[1]}\nurl:    {url}\n结果:   失败(具体原因见前面的错误警告)\n---end]')
